<template>
  <Dialog v-model="dialogVisible" title="授权码" width="450px">
    <section class="flex justify-between">
      <div>{{authorizeCode}}</div>
      <el-tooltip effect="dark" content="复制" placement="top-start">
        <img src="@/assets/imgs/copy-icon.png" alt="" class="w-20px h-20px ml-10px cursor-pointer"
          @click="copyTextToClipboard(authorizeCode)" />
      </el-tooltip>
    </section>
    <template #footer>
      <el-button type="primary" @click="dialogVisible=false">关闭</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import { getTenantId, getTenantList } from '@/utils/auth'

  const dialogVisible = ref(false)
  const authorizeCode = ref()

  const open = async () => {
    getAuthorizationCode()
    dialogVisible.value = true
  }

  const getAuthorizationCode = () => {
    const tenantList = getTenantList() || []
    authorizeCode.value = tenantList.find(e => e.id === getTenantId())?.authorizationCode
  }

  const copyTextToClipboard = (text) => {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(text).then(() => console.log('复制成功'));
    } else {
      const textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
    }
  }

  defineExpose({ open })
</script>